//
//  LBLimitInput.m
//  LandCredit
//
//  Created by Mr.Xr on 2017/4/14.
//  Copyright © 2017年 联壁. All rights reserved.
//

#import "LBLimitInput.h"
#import <objc/runtime.h>
#define LB_LIMIT_INPUT [LBLimitInput sharedInstance]

@implementation UIView (Limit)

- (NSInteger)limitMaxLength {
    NSNumber *number = objc_getAssociatedObject(self, _cmd);
    return [number integerValue];
}

- (void)setLimitMaxLength:(NSInteger)limitMaxLength {
    objc_setAssociatedObject(self, @selector(limitMaxLength), @(limitMaxLength), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSString *)limitRegx {
    return objc_getAssociatedObject(self, _cmd);
}

- (void)setLimitRegx:(NSString *)limitRegx {
    objc_setAssociatedObject(self, @selector(limitRegx), limitRegx, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

@end


@implementation LBLimitInput


static LBLimitInput *g_limitInput;

+ (LBLimitInput *)sharedInstance {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        g_limitInput = [[LBLimitInput alloc] init];
    });
    return g_limitInput;
}

+ (void)limitInputView:(UIView<UITextInput> *)view maxLength:(NSUInteger)length {
    NSAssert([view conformsToProtocol:@protocol(UITextInput)], @"view必须实现UITextInput协议，即view对象当是UITextField或UITextView对象");
    view.limitMaxLength = length;
    [[NSNotificationCenter defaultCenter] addObserver:LB_LIMIT_INPUT selector:@selector(textInputViewDidChangeLimitLength:) name:UITextFieldTextDidChangeNotification object:view];
    [[NSNotificationCenter defaultCenter] addObserver:LB_LIMIT_INPUT selector:@selector(textInputViewDidChangeLimitLength:) name:UITextViewTextDidChangeNotification object:view];
}

- (void)textInputViewDidChangeLimitLength:(NSNotification *)notification {
    UIView<UITextInput> *inputView = (UIView<UITextInput> *)notification.object;
    NSString *key                  = @"text";
    NSString *text                 = [inputView valueForKey:key];
    NSInteger length               = inputView.limitMaxLength;
    if (length > 0 && text.length > length && inputView.markedTextRange == nil) {
        [inputView setValue:[text substringWithRange: NSMakeRange(0, length)] forKey:key];
    }
}

+ (void)limitInputView:(UIView<UITextInput> *)view regX:(NSString *)regx {
    view.limitRegx = regx;
    [[NSNotificationCenter defaultCenter] addObserver:LB_LIMIT_INPUT selector:@selector(textInputViewDidChangeLimitRegx:) name:UITextFieldTextDidChangeNotification object:view];
    [[NSNotificationCenter defaultCenter] addObserver:LB_LIMIT_INPUT selector:@selector(textInputViewDidChangeLimitRegx:) name:UITextViewTextDidChangeNotification object:view];
}

- (void)textInputViewDidChangeLimitRegx:(NSNotification *)notification {
    UIView<UITextInput> *inputView = (UIView<UITextInput> *)notification.object;
    NSString *regx = inputView.limitRegx;
    NSString *key  = @"text";
    NSString *text = [inputView valueForKey:key];
    if (regx && text.length > 0) {
        NSError *error = nil;
        NSRegularExpression *express = [NSRegularExpression regularExpressionWithPattern:regx options:NSRegularExpressionCaseInsensitive error:&error];
        NSRange validRange = [express rangeOfFirstMatchInString:text options:0 range:NSMakeRange(0, text.length)];
        if (validRange.location == NSNotFound) {
            [inputView setValue:nil forKey:key];
        } else {
            [inputView setValue:[text substringFromIndex:validRange.location] forKey:key];
        }
        /** Apis
         [express stringByReplacingMatchesInString:(nonnull NSString *) options:(NSMatchingOptions) range:(NSRange) withTemplate:(nonnull NSString *)];
         NSArray<NSTextCheckingResult *> *matchArray = [express matchesInString:textField.text options:0 range:NSMakeRange(0, textField.text.length)];
         NSTextCheckingResult *result = matchArray.lastObject;
         [express firstMatchInString:(nonnull NSString *) options:(NSMatchingOptions) range:(NSRange)];
         [express rangeOfFirstMatchInString:(nonnull NSString *) options:(NSMatchingOptions) range:(NSRange)];
         */
    }
}

+ (void)limitPhoneInputView:(UIView<UITextInput> *)view {
    [self limitInputView:view maxLength:11];
    [self limitInputView:view regX:@"[^0].*"];
}

+ (BOOL)isEmpty:(NSString *)text {
    return text.length <= 0 || [text isEqualToString:@"nil"] || [text isEqualToString:@"null"] || [text isKindOfClass:[NSNull class]];
}

/**
 * 是否是合法的手机号
 */
+ (BOOL)isValidPhoneNum:(NSString *)text {
    // 不用正则判断
    if ((text.length != 11 || [text hasPrefix:@"0"]) || text.length <= 0) {
        return NO;
    }
    return YES;
    
    ///** 正则判断
//     NSString *phoneRegex = @"^((14[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,0-9])|(17[0-9]))\\d{8}$";
//     NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
//     return [phoneTest evaluateWithObject:text];
     //*/
}

/**
 * 是否是合法的email
 */
+ (BOOL)isValidEmail:(NSString *)text {
    NSString *regex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTestPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [emailTestPredicate evaluateWithObject:text];
}

/**
 * 是否是合法的密码 （8~16 字母、数字、字符）
 * TODO:// 业务需求处理：必须含有字母、数字组合？？？
 */
+ (BOOL)isValidPassword:(NSString *)text {
    if (text.length >= 8 && text.length <= 16) {
        if (![self isVaildPasswordStr:text]) {
            return YES;
        }
    }
    return NO;
}

/**
 *  检测是否纯数字，纯字母，纯字符
 */
+ (BOOL)isVaildPasswordStr:(NSString *)text {
    if (![self isPureLetters:text] &&
        ![self isPureNumandCharacters:text] &&
        ![self isAllCharacterString:text]) {
        return NO;
    }
    return YES;

}

+ (BOOL)isPureLetters:(NSString *)str {
    for(int i = 0; i < str.length; i++){
        unichar c = [str characterAtIndex:i];
        if((c <'A'||c >'Z')&&(c <'a'||c >'z'))
            return NO;
    }
    return YES;
    
}

/**
 *  是否合法身份证
 */
+ (BOOL)isValidIdCard:(NSString *)text {
    if (text.length == 0) {
        return NO;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:text];
}


/**
 *  银行卡验证
 */
+ (BOOL)isBankCard:(NSString *)cardNumber {
    
    if(cardNumber.length == 0) {
        return NO;
    }
    NSString *digitsOnly = @"";
    char c;
    for (int i = 0; i < cardNumber.length; i++) {
        c = [cardNumber characterAtIndex:i];
        if (isdigit(c)) {
            digitsOnly =[digitsOnly stringByAppendingFormat:@"%c",c];
        }
    }
    int sum = 0;
    int digit = 0;
    int addend = 0;
    BOOL timesTwo = false;
    for (NSInteger i = digitsOnly.length - 1; i >= 0; i--) {
        digit = [digitsOnly characterAtIndex:i] - '0';
        if (timesTwo) {
            addend = digit * 2;
            if (addend > 9) {
                addend -= 9;
            }
        } else {
            addend = digit;
        }
        sum += addend;
        timesTwo = !timesTwo;
    }
    int modulus = sum % 10;
    return modulus == 0;
}

/**
 *  验证全为中文
 */
+ (BOOL)checkEmptyString:(NSString *) string {
    
    if (string == nil) return string == nil;
    
    NSString *newStr = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
    return [newStr isEqualToString:@""];
}

// 姓名校验 2~8个中文字,不允许拼音,数字
+ (BOOL)isVaildRealName:(NSString *)realName {
    
    if ([self checkEmptyString:realName]) return NO;
    //一般正常的名字长度不会少于2位并且不超过8位，如果有那就设高一点
    if ([realName length] < 2 || [realName length] > 8) {
        return NO;
    }
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[\u4e00-\u9fa5]+$" options:0 error:NULL];
    
    NSTextCheckingResult *match = [regex firstMatchInString:realName options:0 range:NSMakeRange(0, [realName length])];
    
    NSUInteger count = [match numberOfRanges];
    
    return count == 1;
}

/**
 *  纯数字
 */
+ (BOOL)isPureNumandCharacters:(NSString *)string {
    
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
    if(string.length > 0) {
        return NO;
    }
    return YES;
    
//    if(![self isPureInt:string] || ![self isPureFloat:string]) {
//        return NO;
//    }
//    
//    return YES;
}

//判断是否为整形：


+ (BOOL)isPureInt:(NSString*)string{
    
    NSScanner *scan = [NSScanner scannerWithString:string];
    
    int val;
    
    return[scan scanInt:&val] && [scan isAtEnd];
    
}



//判断是否为浮点形：

+ (BOOL)isPureFloat:(NSString*)string{
    
    NSScanner *scan = [NSScanner scannerWithString:string];
    
    float val;
    
    return[scan scanFloat:&val] && [scan isAtEnd];
    
}


/**
 *  纯特殊字符
 */
+ (BOOL)isAllCharacterString:(NSString *)string
{
    NSString *regex = @"[~`!@#$%^&*()_+-=[]|{};':\",./<>?]{,}/";//规定的特殊字符，可以自己随意添加
    
    //计算字符串长度
    NSInteger str_length = [string length];
    NSInteger allIndex = 0;
    for (int i = 0; i<str_length; i++) {
        //取出i
        NSString *subStr = [string substringWithRange:NSMakeRange(i, 1)];
        if([regex rangeOfString:subStr].location != NSNotFound) {
            //存在
            allIndex++;
        }
    }
    if (str_length == allIndex) {
        //纯特殊字符
        return YES;
    } else {
        //非纯特殊字符
        return NO;
    }
}

/**
 *  检测交易密码是否合法
 */
+ (BOOL)isTransactionPassword:(NSString *)text {
    if (text.length == 6) {
        if ([self isPureNumandCharacters:text]) {
            return YES;
        }
        return NO;
    }
    return NO;
}

@end
